import React, {useEffect, useState} from 'react';
import {useHistory} from "react-router-dom";
import {Button, List, PullToRefresh} from "antd-mobile";

import Input from "../../components/input/Input";
import Txt from "../../components/txt/Txt";

import './goods.less';
import http from "../../model/http";

const Item = List.Item;
const Brief = Item.Brief;
let page = 1;
const h = document.documentElement.clientHeight - 110;
function Goods() {
  const history = useHistory();
  const [load,setLoad] = useState(false),
      [val,SetVal] = useState(''),
      [items,setItems] = useState([]),
      [items2,setItems2] = useState([]),
      [tip,setTip] = useState({tips:'',tagList:[]}),
      [type,setType] = useState(0);

  const getList = async ()=>{
    if(!val) return;
    setLoad(true);
    const _items = await http.post('/bill/trnamesearch',{page:page,items:20,searchTxt:val});
    setTimeout(()=>{setLoad(false)},600)
    if(!_items.data.length) return;
    page++;
    setType(0);
    setItems([...items,..._items.data]);
  }


  useEffect(()=>{
    (async ()=>{
      const _items = await http.post('/bill/searchInit',{customerCrmId:history.location.state.customerCrmId});
      setTip({tips:_items.data.length?_items.tips:'',tagList:_items.tagList});
      setType(_items.tagList.length?_items.type:0);
      setItems2(_items.data);
    })()

    return ()=>{page=1};

    // eslint-disable-next-line
  },[])

  const money = item =>{
    item.expert_id = item.expert_id?item.expert_id:'';
    history.push('/goods/money'+window.location.search,{outUser:history.location.state,item});
  }


  return (
    <div className='v-goods'>
      <Input onSubmit={getList} onChange={SetVal} placeholder='可根据顾客的需求搜索项目...' />

      <PullToRefresh direction='up' onRefresh={getList} refreshing={load} style={{height:h, overflow:'auto'}}>
        {type === 1 && (
            <div className='g-mt10 g-ov'>
              <Txt className='g-mb10'>顾客意向标签:</Txt>
              {tip.tagList && tip.tagList.map((i,idx)=>(
                  <Button key={idx} size='small' inline className='g-mr10'>{i.topClassName}</Button>
              ))}
            </div>
        )}
        {tip.tips && <Txt className='g-mt10'>{tip.tips}</Txt>}

        <List className='g-mt10'>
          {(items.length?items:items2).map((i,idx)=>(
              <Item multipleLine wrap className='g-mb10 g-bdrs12'
                    key={idx}
                    extra={<Button type='primary' size='small' inline onClick={()=>{money(i)}}>开单</Button>}>
                {i.displayName}
                <Brief>
                  <p className='g-f12'>
                    <span className='g-mr10 h-cf61'>优惠价:{i.price}元</span>
                    <del>原价:{i.lowestPrice}元</del>
                  </p>
                </Brief>
              </Item>
          ))}
        </List>

      </PullToRefresh>
    </div>
  )
}

export default Goods;